#!/usr/bin/env python_
# -*- coding: utf-8 -*-

import os, pickle
import requests
from bs4 import BeautifulSoup

dest = "http://xyxxw.forestpolice.net"

def getlink(index):
    r = requests.get(dest+"/yzap/list.htm")
    htmldoc = r.text

    soup = BeautifulSoup(htmldoc, "html5lib")
    # print(soup.prettify())
    p = []
    return soup.find_all('a', target='_blank')[index].get('href')
    
def __getRawEventList(index):
    x = getlink(index)
    # print llist
    ans = [] 
    r = requests.get(dest+x)
    htmldoc = r.text
    # print htmldoc
    soup = BeautifulSoup(htmldoc, 'html5lib')
    
    dictEvent = {}
    
    # seqKey_dictEvent = ['time', 'theme', 'host', 'dept', 'attendee', 'place']
    seqKey_dictEvent = ['time', 'theme', 'location', 'attendee']
    
    mainTable = soup.find('table', 'wp_editor_art_paste_table')
    # print mainTable.prettify().encode('utf-8')
    for tr in mainTable.find_all('tr'):
        dictEvent = dictEvent.fromkeys(seqKey_dictEvent)
        try:
            if tr.td.get_text().replace(u'\xa0', u'') == u'时间':
                continue;
            seqValue_dictEvent = [];
            for td in tr.find_all('td'):
                seqValue_dictEvent.append(td.get_text().replace(u'\xa0', u''))
            for i in range(4):
                dictEvent[seqKey_dictEvent[i]] = seqValue_dictEvent[i]               
            listEvent.append(dictEvent);
        except AttributeError:
            continue
    return listEvent;

def getEventList(index):
    try:
        source = pickle.load(open('event.pickle', 'r'))
    except EOFError:
        source = {}
    rawDict = {}
    rawList = __getRawEventList(index)
    for i in rawList:
        timestr = i['time']
        mon = timestr[2:].split(u'月')[0]
        dat = timestr[2:].split(u'月')[1].split(u'日')[0]
        i['month'] = int(mon)
        i['day'] = int(dat)
        if (int(mon) < 10):
            mon = '0' + mon;
        if (int(dat) < 10):
            dat = '0' + dat;
        key = mon+dat;
        rawDict[key] = i   
    source.update(rawDict)
    pickle.dump(source, open('event.pickle', 'w'))
    return source
    
if __name__ == '__main__':
    l = getEventList(0)
    for x in l:
        print x['day']